package com.oxbix.spanlogistics.utils;

import android.graphics.Bitmap;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by chen on 18/1/15.
 */

public class FileUtils {

    public static final String KYE_ROOT_FILE_NAME = "kye";
    public static String DOWNLOAD_FILE = "downloadFile";


    public static File getKyeRootFolder() {
        File root = new File(getSDCardFolder(), KYE_ROOT_FILE_NAME);
        if (!root.exists()) {
            root.mkdirs();
        }

        return root;
    }

    public static File getSDCardFolder() {
        File root = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            root = Environment.getExternalStorageDirectory();
        } else {
            root = Environment.getDataDirectory();
        }

        return root;
    }

    public static String getKyeRoot() {
        return getKyeRootFolder().getAbsolutePath();
    }


    public static String getDownloadFilePath() {
        String path = getKyeRoot() + File.separator + DOWNLOAD_FILE;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        return path;
    }

    public static boolean saveBitmapInFile(Bitmap bitmap, String savePath) {
        FileOutputStream fos = null;
        boolean isSuccess = false;
        try {
            if (bitmap == null) {
                releaseResource(bitmap);
                return isSuccess;
            }
            fos = new FileOutputStream(savePath);
            //            Bitmap bmSize = ImageUtils.comp(bitmap,200);  //按图片比例压缩
            //            Bitmap bmLength = ImageUtils.compressImage(bmSize, 200); //质量压缩 图片不大于500KB
            isSuccess = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            releaseResource(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return isSuccess;
    }

    public static void releaseResource(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }
}
